﻿using System;
using System.Text.RegularExpressions;
using UnityEngine;

namespace Nirvana
{
    public static class RectExtensions 
    {
        private static Regex regex;
        public  static Rect Parse(string txt)
        {
            Rect result;
            if(!TryParse(txt,out result))
            {
                string message = string.Format("The string {0} can not convert to Rect.", txt);
                throw new FormatException(message);
            }
            return result;
        }

        public static bool TryParse(string text, out Rect rect)
        {
            if (regex == null)
            {
                regex = new Regex("^\\(x:(.*), y:(.*), width:(.*), height:(.*)\\)$");
            }
            Match match = regex.Match(text);
            if (!match.Success || match.Groups.Count != 5)
            {
                rect = Rect.zero;
                return false;
            }
            float num;
            if (!float.TryParse(match.Groups[1].Value, out num))
            {
                rect = Rect.zero;
                return false;
            }
            float num2;
            if (!float.TryParse(match.Groups[2].Value, out num2))
            {
                rect = Rect.zero;
                return false;
            }
            float num3;
            if (!float.TryParse(match.Groups[3].Value, out num3))
            {
                rect = Rect.zero;
                return false;
            }
            float num4;
            if (!float.TryParse(match.Groups[4].Value, out num4))
            {
                rect = Rect.zero;
                return false;
            }
            rect = new Rect(num, num2, num3, num4);
            return true;
        }
    }
}

